package com.example.examsystem.controller;

import com.example.examsystem.dto.LoginRequest;
import com.example.examsystem.dto.LoginResponse;
import com.example.examsystem.dto.RegisterRequest;
import com.example.examsystem.dto.UserDto;
import com.example.examsystem.service.AuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody @Valid LoginRequest loginRequest) {
        try {
            log.info("Login attempt for user: {}", loginRequest.getUsername());
            log.info("Request data: {}", loginRequest);
            
            LoginResponse response = authService.login(loginRequest);
            log.info("Login successful for user: {}", loginRequest.getUsername());
            
            return ResponseEntity.ok(response);
        } catch (BadCredentialsException e) {
            log.error("Bad credentials for user: {}, error: {}", loginRequest.getUsername(), e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("success", false, "message", "用户名或密码错误"));
        } catch (Exception e) {
            log.error("Login error for user: {}: ", loginRequest.getUsername(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("success", false, "message", "登录失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody @Valid RegisterRequest registerRequest) {
        try {
            UserDto user = authService.register(registerRequest);
            return ResponseEntity.ok(Map.of("success", true, "data", user));
        } catch (Exception e) {
            log.error("Registration error: ", e);
            return ResponseEntity.badRequest()
                .body(Map.of("success", false, "message", e.getMessage()));
        }
    }
    
    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser() {
        try {
            UserDto user = authService.getCurrentUser();
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            log.error("Get current user error: ", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("success", false, "message", "获取用户信息失败"));
        }
    }
    
    @PostMapping("/refresh")
    public ResponseEntity<?> refreshToken() {
        try {
            LoginResponse response = authService.refreshToken();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("Refresh token error: ", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("success", false, "message", "刷新令牌失败"));
        }
    }
    
    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        authService.logout();
        return ResponseEntity.ok(Map.of("success", true, "message", "退出成功"));
    }
}




